<?php
class ModuleBest extends Controller {
	function fetch() {
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$image    =& $this->locator->get('image');
		$tax      =& $this->locator->get('tax');
		$url      =& $this->locator->get('url');
		$template =& $this->locator->get('template');
		
		if (!$config->get('best_status')) { return; }

	  	$language->load('extension/module/best.php');
	  	
	  	$max_rows=$config->has('best_max_rows')?$config->get('best_max_rows'):$config->get('config_max_rows');
	  	
  	  	$view = $this->locator->create('template');

		$view->set('tpl', $template);
  	  	
  	  	$view->set('heading_title', $language->get('heading_title'));

		$sql = "SELECT product.*, order_product.order_product_id, order_product.order_id, SUM(order_product.quantity) as TotalOrdered, product_description.product_id, product_description.language_id, product_description.name, image.* FROM product, order_product, order_history, product_description, image WHERE product.product_id = product_description.product_id AND product_description.name = order_product.name AND product.image_id = image.image_id AND product.status ='1' AND product_description.language_id = '" . (int)$language->getId() . "' GROUP BY order_product.name ORDER BY TotalOrdered, rand() DESC limit ?";
		$products = $database->getRows($database->parse($sql, $language->getId(), $max_rows));
		
		if (!$products) { return; } //don't show box if there are no products
		
		$product_data = array();
		
		foreach ($products as $product) {
			
			$price_old = null;
			
			$special = $database->getRow("select distinct * from product_special where product_id = '" . $product['product_id'] . "' and status = '1' and date_start <= now() and date_end > now()");
			
			if ($special) {
				$price_old = $product['price'];
				if ($special['prefix'] == '%') {
					$product['price'] -= $product['price'] * ($special['discount']/100);
				} elseif ($special['prefix'] == '-') {
					$product['price'] -= $special['discount'];
				} else {
					$product['price'] = $special['discount'];
				}
			}
			
			$product_data[] = array(
				'name'  	=> $product['name'],
				'href'  	=> $url->href('product', FALSE, array('product_id' => $product['product_id'])),
				'thumb' 	=> $image->resize($product['filename'], $config->get('config_image_width'), $config->get('config_image_height')),
				'price' 	=> $currency->format($tax->calculate($product['price'], $product['tax_class_id'], $config->get('config_tax'))),
				'price_old' => (isset($price_old))?$currency->format($tax->calculate($price_old, $product['tax_class_id'], $config->get('config_tax'))):NULL,
			);
		}
		
		$view->set('products', $product_data);

		return $view->fetch('module/best.tpl');
	}
}
?>
